import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
  {
    path: '/',
    name: 'root',
    component: () => import('@/views/BaseView.vue'),
    redirect: '/home',
    children: [
      {
        name: "home",
        path: '/home',
        component: () => import('@/views/HomeView.vue'),
        meta: {
          title: '首页',
          requireLogin: false
        }
      },
      {
        name: "question",
        path: '/question/:id',
        component: () => import('@/views/QuestionView.vue'),
        meta: {
          title: '提问详情',
          requireLogin: false
        }
      },
      {
        name: "answer",
        path: '/answer/:id',
        component: () => import('@/views/AnswerView.vue'),
        meta: {
          title: '答案详情',
          requireLogin: false
        }
      },
      {
        name: "login",
        path: '/login',
        component: () => import('@/views/LoginView.vue'),
        meta: {
          title: '账号登录',
          requireLogin: false
        }
      },
      {
        name: "reg",
        path: '/reg',
        component: () => import('@/views/RegView.vue'),
        meta: {
          title: '账号注册',
          requireLogin: false
        }
      },
      {
        name: "publish",
        path: '/publish',
        component: () => import('@/views/PublishView.vue'),
        meta: {
          title: '发布提问',
          requireLogin: true
        }
      },
      {
        name: "ucenter",
        path: '/ucenter',
        component: () => import('@/views/UcenterView.vue'),
        meta: {
          title: '个人中心',
          requireLogin: true
        }
      },
      {
        name: "avatar",
        path: '/avatar',
        component: () => import('@/views/AvatarView.vue'),
        meta: {
          title: '更新头像',
          requireLogin: true
        }
      },
      {
        name: "404",
        path: '/404',
        component: () => import('@/views/NotFound.vue'),
        meta: {
          title: '404-资源不存在',
          requireLogin: false
        }
      },
      {
        name: "notfound",
        path: '/:pathMatch(.*)*',
        component: () => import('@/views/NotFound.vue'),
        meta: {
          title: '404-资源不存在',
          requireLogin: false
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  linkExactActiveClass: 'active',
  scrollBehavior() {
    return { top: 0 }
  }
})

router.beforeResolve(function (to, from, next) {
  if (to.meta.requireLogin) {
    const token = localStorage.getItem('token')
    if (!token) {
      return next({ name: 'login' })
    }
    document.title = to.meta.title
  }
  next()
})

export default router
